package com.jrtc.base.util;

import com.jrtc.base.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

import static java.util.Objects.isNull;

@Component
public class MinioUtil {
    /**
     * 空字符串
     */
    private static final String NULLSTR = "";

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

//filename

    /**
     * 文件上传
     * */
    public String uploadFile(MultipartFile file, String source, String business) throws Exception {
        String fileName = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (isNull(extension) || NULLSTR.equals(extension.trim())) {
            switch (file.getContentType()) {
                case "image/png":
                    extension = "png";
                case "image/jpg":
                    extension = "jpg";
                case "image/jpeg":
                    extension = "jpeg";
                case "image/bmp":
                    extension = "bmp";
                case "image/gif":
                    extension = "gif";
                default:
                    return "";
            }
        }

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

        fileName = dateFormat.format(now) + "/" + UUIDUtil.fastUUID().toString() + "." + extension;
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(source + "/" + business + "/" + fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);

//        return "http://106.38.39.137:9000/" + minioConfig.getBucketName() + "/" + source + "/" + business + "/" + fileName;
//        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + source + "/" + business + "/" + fileName;
        return minioConfig.getBucketName() + "/" + source + "/" + business + "/" + fileName;
    }


}
